/*
    This file is part of qmessages.
    Copyright (C) 2010  Jason Newton <nevion@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef QMSGIO_QMESSAGEENDPOINT_H
#define QMSGIO_QMESSAGEENDPOINT_H

#include <memory>
#include <QByteArray>
#include <QAbstractSocket>
#include <QObject>

#include "QMessage.h"

namespace qmsgio{

class QMessageEndpoint: public QObject{
    Q_OBJECT
    public:
        QIODevice *transport;
        QMessageEndpoint(QIODevice *transport, QObject *parent = 0);
        virtual ~QMessageEndpoint();

        enum receive_state_t{
            MESSAGE_START,
            BUFFER_MINHEADER,
            READ_MINHEADER,
            BUFFER_FIXED,
            READ_FIXED,
            BUFFER_VARIABLE,
            READ_VARIABLE,
            MESSAGE_COMPLETE
        };
        receive_state_t receive_state;
        QByteArray buffer;
        std::unique_ptr<QMessage> msg;
        qint32 buffer_nread;
        qint32 buffer_nexpect;

        virtual void sendMsg(QMessage *msg);

    public slots:
        virtual void onReceiveData();
        virtual bool onReceiveMsg(QMessage *msg);
        virtual bool onInvalidMsg(QMessage *msg, receive_state_t receive_state);
    signals:
        void receiveMsg(QMessage *msg);
        void invalidMsg(QMessage *msg);

    private:
        void assemble();

};

}
#endif
